package com.xiaoq.matrix.activity.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGeneratorUtils;
import com.xiaoq.matrix.activity.entity.ActivityEntity;
import com.xiaoq.matrix.activity.repository.IActivityRepository;
import com.xiaoq.vo.PagingVo;

@Repository
public class ActivityRepositoryImpl implements IActivityRepository{
	
	@Autowired
	private Datastore dataStore;

	private static final Logger LOG = LoggerFactory.getLogger(ActivityRepositoryImpl.class);
	
	@Override
	public boolean addActivity(ActivityEntity activity) {
		if(activity!=null){
			dataStore.save(activity);
			return true;
		}
		return false;
		
		
	}

	@Override
	public boolean delActivity(String id) {
		if(id!=null){
			Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
			activityQuery.field(IdGeneratorUtils.IDGENERATOR).equal(id);
			dataStore.delete(activityQuery);
			return true;
		}
		LOG.error("传递的activityId为空！");
		return false;
	}

	@Override
	public boolean updateActivityStatus(String id) {
		LOG.info("活动Id:"+id);
		Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
		activityQuery.field(IdGeneratorUtils.IDGENERATOR).equal(id);
		UpdateOperations<ActivityEntity> updateOperation = dataStore.createUpdateOperations(ActivityEntity.class);
		if(StringUtils.isNotEmpty(id)){
			ActivityEntity activity = activityQuery.get();
			if(activity!=null){
				if("1".equals(activity.getStatus())||activity.getStatus()==null){
					updateOperation.set("status", "0"); 
//					updateOperation.set("pubTime", System.currentTimeMillis());
					updateOperation.set("updatedAt", System.currentTimeMillis());
					dataStore.update(activityQuery, updateOperation);
					return true;
				}
				LOG.debug("该活动已经结束！");
					
			}
			LOG.info("系统已不存在这种活动！");
			
		}
		LOG.error("请不要传递空的activityId");
		return false;
	}

	@Override
	public ActivityEntity findActivity(String id) {
		ActivityEntity activity = null;
		if(StringUtils.isNotEmpty(id)){
			activity = dataStore.get(ActivityEntity.class, id);
		}else{
			LOG.error("activityId值不能为空!");
		}
		
		return activity;
	}

	@Override
	public List<ActivityEntity> findActivityListByCity2G(String cityCode,String key, PagingVo pvo) {
		Integer ps = pvo.getPs();
		Integer pn  = (pvo.getPn()-1)*ps;
		Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
		activityQuery.field("zoneCity").equal(cityCode);
		if(StringUtils.isNotBlank(key)){
			activityQuery.field("title").contains(key);
		}
		Long total = activityQuery.count();
		pvo.setTc(total);
		activityQuery.order("-status,-endTime").offset(pn).limit(ps);
		List<ActivityEntity> activityList = null;

		activityList = activityQuery.asList();
		return activityList;
	}

	@Override
	public List<ActivityEntity> findActivityListByOrgnizer(String orgnizerId, String title, Long pubStart, Long pubEnd,
			String authStatus,PagingVo pvo) {
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;

		Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
		activityQuery.field("orgnizerId").equal(orgnizerId);
		if (StringUtils.isNotEmpty(authStatus)) {
			activityQuery.field("authStatus").equal(authStatus);
		}
		if (StringUtils.isNotEmpty(title)) {
			activityQuery.field("title").contains(title);
		}
		if (pubStart != null) {
			activityQuery.filter("pubTime >=", pubStart);
		}
		if (pubEnd != null) {
			activityQuery.filter("pubTime <=", pubEnd);
		}

		Long total = 0L;
		total = activityQuery.count();

		if (total != 0L) {
			activityQuery.order("-status,-pubTime,-createdAt").offset(pn).limit(ps);
		}
		pvo.setTc(total);
		List<ActivityEntity> activityList = new ArrayList<ActivityEntity>();
		activityList = activityQuery.asList();
		return activityList;
	}

	@Override
	public List<ActivityEntity> findActivityListByCity(String cityCode, PagingVo pvo) {
		Integer ps = pvo.getPs();
		Integer pn  = (pvo.getPn()-1)*ps;
		
		Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
		List<ActivityEntity> activityList = null;
		if(StringUtils.isNotEmpty(cityCode)){
			activityQuery.field("zoneCity").equal(cityCode);
			if(activityQuery.count()==0){
				activityQuery = dataStore.find(ActivityEntity.class);
				cityCode = "520100";
				activityQuery.field("zoneCity").equal(cityCode);
			}
			Long total = activityQuery.count();
			if(total!=0L){
				pvo.setTc(total);
				// 排序结果不对的原因可能是有的数据没有pubTime这儿属性
				activityQuery.order("-status,-pubTime,-createdAt").offset(pn).limit(ps);
				activityList = activityQuery.asList();
			}else{
				LOG.debug("按城市查询结果为空！");
			}
		}
		return activityList;
	}

	@Override
	public boolean updateActivity(ActivityEntity activity) {
		
		if(activity!=null){
			String activityId = activity.getId();
			if(StringUtils.isNotEmpty(activityId)){
				Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class).field(IdGeneratorUtils.IDGENERATOR).equal(activityId);
				UpdateOperations<ActivityEntity> activityUpdate = dataStore.createUpdateOperations(ActivityEntity.class);
				
				String title = activity.getTitle();
				if(StringUtils.isNotEmpty(title)){
					activityUpdate.set("title", title);
				}
				String content = activity.getContent();
				if(StringUtils.isNotEmpty(content)){
					activityUpdate.set("content", content);
				}
				List<String> tags = activity.getTags();
				if(tags!=null){
					activityUpdate.set("tags", tags);
				}
				Long startTime = activity.getStartTime();
				if(startTime!=null){
					activityUpdate.set("startTime", startTime);
				}
				Long endTime = activity.getEndTime();
				if(endTime!=null){
					activityUpdate.set("endTime", endTime);
				}
				String memo = activity.getMemo();
				if(memo!=null){
					activityUpdate.set("memo", memo);
				}
				String postUrl = activity.getPostUrl();
				if(postUrl!=null){
					activityUpdate.set("postUrl", postUrl);
				}
				String zoneProvince = activity.getZoneProvince();
				if(StringUtils.isNotEmpty(zoneProvince)){
					activityUpdate.set("zoneProvince",zoneProvince);
				}
				
				String zoneCity = activity.getZoneCity();
				if(StringUtils.isNotEmpty(zoneCity)){
					activityUpdate.set("zoneCity",zoneCity);
				}
				
				String zoneDistrict = activity.getZoneDistrict();
				if(StringUtils.isNotEmpty(zoneDistrict)){
					activityUpdate.set("zoneDistrict",zoneDistrict);
				}
				String orgnizerId = activity.getOrgnizerId();
				if(StringUtils.isNotEmpty(orgnizerId)){
					activityUpdate.set("orgnizerId",orgnizerId);
				}
				
				String orgnizerInfo = activity.getOrgnizerInfo();
				if(StringUtils.isNotEmpty(orgnizerInfo)){
					activityUpdate.set("orgnizerInfo",orgnizerInfo);
				}
				String orgnizerType = activity.getOrgnizerType();
				if(StringUtils.isNotEmpty(orgnizerType)){
					activityUpdate.set("orgnizerType",orgnizerType);
				}
				
				String attendMethod = activity.getAttendMethod();
				if(StringUtils.isNotEmpty(attendMethod)){
					activityUpdate.set("attendMethod",attendMethod);
				}
				String contact = activity.getContact();
				if(StringUtils.isNotEmpty(contact)){
					activityUpdate.set("contact",contact);
				}
				
				Integer maxParticipants = activity.getMaxParticipants();
				if(maxParticipants!=null){
					activityUpdate.set("maxParticipants",maxParticipants);
				}
				
				String address = activity.getAddress();
				if(StringUtils.isNotEmpty(address)){
					activityUpdate.set("address",address);
				}
				
				 Double longitude = activity.getLongitude();
				 if(longitude!=null){
					 activityUpdate.set("longitude",longitude);
				 }
				 
				 Double latitude = activity.getLatitude();
				 if(latitude!=null){
					 activityUpdate.set("latitude",latitude);
				 }
				 
				 String status = activity.getStatus();
				 if(StringUtils.isNotEmpty(status)){
					 activityUpdate.set("status",status);
				 }
				
				 String needOrder = activity.getNeedOrder();
				 if(StringUtils.isNotEmpty(needOrder)){
					 activityUpdate.set("needOrder",needOrder);
				 }
				 
				 List<String> recmReasons = activity.getRecmReasons();
				 if(recmReasons!=null){
					 activityUpdate.set("recmReasons",recmReasons);
				 }
				 Long pubTime = activity.getPubTime();
				 if(pubTime!=null){
					 activityUpdate.set("pubTime",pubTime);
				 }
				activityUpdate.set("updatedAt", System.currentTimeMillis());
				dataStore.update(activityQuery, activityUpdate);
				return true;
				
			}
		}else{
			LOG.error("activity为空,报空指针异常！");
		}
		
		return false;
	}

	@Override
	public ActivityEntity findActivity2C(String id) {
		ActivityEntity activity = null;
		if(StringUtils.isNotEmpty(id)){
			Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
			activityQuery.field(IdGeneratorUtils.IDGENERATOR).equal(id).field("authStatus").equal("20");
			activity = activityQuery.get();
			return activity;
		}else{
			LOG.error("activityId值不能为空!");
		}
		
		return activity;
	}

	@Override
	public List<ActivityEntity> findActivityListByCity2C(String cityCode, String district, PagingVo pvo) {
		Integer ps = pvo.getPs();
		Integer pn = (pvo.getPn() - 1) * ps;

		Query<ActivityEntity> activityQuery = dataStore.find(ActivityEntity.class);
		List<ActivityEntity> activityList = null;
		if (StringUtils.isNotBlank(cityCode)) {
			activityQuery.field("zoneCity").equal(cityCode);
		}
		if(StringUtils.isNotBlank(district)){
			activityQuery.field("zoneDistrict").equal(district);
		}
		if (activityQuery.count() == 0) {
			activityQuery = dataStore.find(ActivityEntity.class);
			activityQuery.field("zoneCity").equal(cityCode);
		}
		if (activityQuery.count() == 0) {
			activityQuery = dataStore.find(ActivityEntity.class);
			cityCode = "520100";
			activityQuery.field("zoneCity").equal(cityCode);
		}
		activityQuery.field("authStatus").equal("20");
		Long total = activityQuery.count();
		if (total != 0L) {
			pvo.setTc(total);
			// activityQuery.order("-status,-pubTime,-createdAt").offset(pn).limit(ps);
			activityQuery.order("-status,-endTime").offset(pn).limit(ps);
			activityList = activityQuery.asList();
		} else {
			LOG.debug("按城市查询结果为空！");
		}

		return activityList;
	}

}
